<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="videoForm" :rules="rules" ref="videoRef" label-width="100px" class="videoForm">
        <el-form-item label="视频名称" prop="videoname">
          <el-input style="width: 300px" v-model="videoForm.videoname" placeholder="请输入视频名称"></el-input>
        </el-form-item>
        
        <el-form-item required label="视频文件" prop="videourl">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png,mp4"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
          >
          <video style=" border: 1px solid #e9e9e9;" width="160" height="120" v-if="videoForm.videourl" controls autoplay> <source :src="videoForm.videourl" class="avatar" ></video>
            <!-- <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="videoForm.videoscoverimg" :src="videoForm.videoscoverimg" class="avatar"> -->
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序值" prop="order">
          <el-input type="number" max='200' v-model="videoForm.order"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from '@/utils'
export default {
  name: 'Addvideo',
  setup() {
    const { proxy } = getCurrentInstance()
    const videoRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    let { id,course_id } = route.query
    const state = reactive({
      uploadImgServer,
      token: localGet('token') || '',
      id: id,
      videoForm: {
        videoname: '',
        videourl:'',
        order:'',
        course_id:course_id,
      },
      rules: {
        videourl: [
          { required: 'true', message: '请上传视频', trigger: ['change'] }
        ],
        videoname: [
          { required: 'true', message: '请填写视频名称', trigger: ['change'] }
        ],
        order: [
          { required: 'true', message: '请填写排序值', trigger: ['change'] }
        ],
      },
    })
    onMounted(() => {
      if (id) {
        axios.get(`/video/${id}`).then(res => {
          // const { videos, firstCategory, secondCategory, thirdCategory } = res
          // console.log('videos',videos)
          const videos = res;
          console.log(videos,1234);
          state.videoForm = {
            videoname: videos.videoname,
            videourl: videos.videourl,
            order: videos.order,
            course_id:videos.course_id
          }
        })
      }
    })
    const submitAdd = () => {
      videoRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          let httpOption = axios.post
          let params = {
            videoname: state.videoForm.videoname,
            videourl: state.videoForm.videourl,
            order: state.videoForm.order,
            course_id:state.videoForm.course_id
          }
          if (params.videoname.length > 128) {
            ElMessage.error('视频名称不能超过128个字符')
            return
          }
          console.log('params', params)
          if (id) {
            params.id = id
            // 修改课程使用 put 方法
            httpOption = axios.put
          }
          httpOption('/video', params).then(() => {
            ElMessage.success(id ? '修改成功' : '添加成功')
            let queryId = id ? state.videoForm.course_id : course_id
            router.push({ path: '/good_video',query:{ id :queryId}} )
            // router.push({ path: '/add', query: { id } })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png','ogg','mp4'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png、mp4 格式的图片')
        return false
      }
    }
    const handleUrlSuccess = (val) => {
      state.videoForm.videourl = val.data || ''
    }
    return {
      ...toRefs(state),
      videoRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>